#include "i2cm.h"
#include "config.h"
#include "io_PCF8574.h"

unsigned char IO_Present = 0;

//-----------------------------------------------------------
// Check if the PCF8574 for inputs present (dev = 0..3)
// on PCF8574 input i/o expander the A2 pin is low
//-----------------------------------------------------------
unsigned char CheckInput_PCF8574(unsigned char dev)
{
	unsigned char present = 0;
	if (dev <= 3)
	{
		if (!i2c_start(DEV_PCF8574 + (dev<<1) + I2C_WRITE))
  			present = 1;
		i2c_stop();
		if (present == 1)
			IO_Present |= (0x01 << dev);
		else
			IO_Present &= ~(0x01 << dev);
	}
	return present;
}

//-----------------------------------------------------------
// Check if the PCF8574 for outputs present (dev = 0..3)
// on PCF8574 output i/o expander the A2 pin is high
//-----------------------------------------------------------
unsigned char CheckOutput_PCF8574(unsigned char dev)
{
	unsigned char present = 0;
	if (dev <= 3)
	{
		if (!i2c_start(DEV_PCF8574 + ((dev | 0x04) << 1) + I2C_WRITE))
  			present = 1;
		i2c_stop();
		if (present == 1)
			IO_Present |= (0x10 << dev);
		else
			IO_Present &= ~(0x10 << dev);
	}
	return present;
}

//-----------------------------------------------------------
// Read byte from PCF8574 input port
//-----------------------------------------------------------
unsigned char ReadI2C_Port(unsigned char dev, unsigned char *value)
{
	if (i2c_start(DEV_PCF8574 + (dev << 1) + I2C_READ) == 0)
	{
    	(*value) = i2c_readNak();
    	i2c_stop();
		IO_Present |= (0x01 << dev);
		return 1;
  	}
	IO_Present &= ~(0x01 << dev);
  	return 0;
}
//-----------------------------------------------------------
// Write byte to PCF8574 output port
//-----------------------------------------------------------
unsigned char WriteI2C_Port(unsigned char dev, unsigned char value)
{
	if (i2c_start(DEV_PCF8574 + ((dev | 0x04) << 1) + I2C_WRITE) == 0)
	{
		i2c_write(value);
		i2c_stop(); 
		IO_Present |= (0x10 << dev);
		return(1);
	}
	IO_Present &= ~(0x10 << dev);
	return(0);
}
